const app = getApp();
const rootPath = xhs.env.USER_DATA_PATH;
const typeArr = [
  {
    type: "pdf",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/PDF.png",
  },
  {
    type: "docx",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/docx.png",
  },
  {
    type: "doc",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/docx.png",
  },
  {
    type: "xlsx",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/xlsx.png",
  },
  {
    type: "xls",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/xlsx.png",
  },
  {
    type: "pptx",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/PPT.png",
  },
  {
    type: "ppt",
    src: "https://statics.offcn.com/hb/pc/images/wxxcx/download/PPT.png",
  },
];
const platform = app.globalData.platform;
const compareVersion = app.methods.compareVersion(
  app.globalData.version,
  "2.11.0"
);
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showStatus: false,
    fileModal: true,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log(app.globalData.version);
    let { src, type, name, url } = options;
    this.setData({
      src,
      type,
      name,
      url,
      PrivacyAuthorization: app.globalData.PrivacyAuthorization,
    });
    if (type === "file") {
      this.getFileType(url);
    }
  },
  async download(e) {
    if (this.data.type === "file") {
      let { id, name, type, url } = this.data;
      xhs.showLoading({
        title: "资源加载中",
      });
      let tempFilePath = await this.downloadFile();
      this.setData({
        tempFilePath,
      });
      xhs.hideLoading();
      this.fileModal();
    } else {
      if (app.globalData.PrivacyAuthorization) {
        this.setData({
          isShowAuth2: !0,
        });
      } else {
        if (this.data.type == "image") {
          xhs.getImageInfo({
            src: this.data.src,
            success(getImageInfoRes) {
              // console.log(getImageInfoRes)
              if (getImageInfoRes.errMsg == "getImageInfo:ok") {
                xhs.saveImageToPhotosAlbum({
                  filePath: getImageInfoRes.path,
                  success(saveImageToPhotosAlbumRes) {
                    // console.log(saveImageToPhotosAlbumRes)
                  },
                });
              }
            },
          });
        } else if (this.data.type == "imageBase64") {
          this.base64ImageHandle(this.data.src);
        }
      }
    }
  },
  /** base64图片保存 */
  base64ImageHandle(base64) {
    // 指定图片的临时路径
    const time = Date.parse(new Date());
    const path = `${xhs.env.USER_DATA_PATH}/${time}.png`;
    // 获取小程序的文件系统
    const fsm = xhs.getFileSystemManager();
    // 把arraybuffer数据写入到临时目录中
    fsm.writeFile({
      filePath: path,
      data: base64.replace(/^data:image\/\w+;base64,/, ""),
      encoding: "base64",
      success: () => {
        xhs.showModal({
          title: "保存图片",
          content: "保存图片到手机相册？",
          confirmColor: "#be3a34",
          success: (result) => {
            if (result.confirm) {
              // 把临时路径下的图片，保存至相册
              xhs.saveImageToPhotosAlbum({
                filePath: path,
                success: () => {
                  xhs.showToast({
                    title: "保存成功",
                    icon: "success",
                    duration: 2000,
                  });
                },
              });
            }
          },
        });
      },
    });
  },
  /** 判定文档类型 */
  getFileType(url) {
    let arr1 = url.split(".");
    let arr2 = url.split("/");
    let type = arr1[arr1.length - 1].toLowerCase();
    let name = arr2[arr2.length - 1];
    let src = typeArr.filter((item) => item.type === type);
    this.setData({
      iconSrc: src[0].src,
      fileName: name,
      fileType: type,
    });
  },
  /** downloadFile 方法 */
  downloadFile() {
    return new Promise((resolve, reject) => {
      const links = this.upgradeToHttps(this.data.url);
      const sufInx = links.lastIndexOf(".");
      if (sufInx === -1) {
        xhs.showToast({
          title: "链接错误",
          icon: "none",
        });
        return;
      }
      let fileType = "";
      fileType = links.substring(sufInx + 1).split(" ")[0];
      let fileTypeArr = ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"];
      if (!fileTypeArr.includes(fileType)) {
        xhs.showToast({
          title: "只能打开.doc/.docx/.xls/.xlsx/.ppt/.pptx/.pdf文件格式",
          icon: "none",
        });
        return;
      } else {
        this.setData({
          fileType,
        });
        const uploadTask = xhs.downloadFile({
          // 示例 url，并非真实存在
          url: links,
          success: function (res) {
            const filePath = res.tempFilePath;
            resolve(filePath);
          },
        });
      }
    });
  },
  /** 打开文档 */
  openFile() {
    let { tempFilePath, fileType } = this.data;
    xhs.openDocument({
      filePath: tempFilePath,
      fileType: fileType,
      success: function (res) {
        console.log(res);
        console.log("成功打开了");
        xhs.hideLoading();
      },
      fail: function (err) {
        console.log(err);
      },
      complete: function (res) {
        console.log(res);
      },
    });
  },
  /* 下载到本地 */
  saveFiles() {
    let { tempFilePath } = this.data;
    const fs = xhs.getFileSystemManager();
    fs.saveFile({
      tempFilePath, // 临时存储文件路径
      // filePath, // 可选：要存储的文件路径
      success: (res) => {
        console.log("文件保存成功:", res.savedFilePath); // 存储后的文件路径
      },
      fail: (err) => {
        console.error("文件保存失败:", err);
      },
      complete: () => {
        console.log("文件保存操作完成");
      },
    });
  },
  /** 选择其它方式保存 */
  choiceSaveMethods() {
    this.setData({
      showStatus: true,
    });
  },
  onActionHide: function () {
    console.log("ActionSheet关闭了");
  },
  /**验证https协议 */
  upgradeToHttps(url) {
    // 使用正则表达式检查URL是否以http://开始
    if (url.startsWith("http://")) {
      // 将http替换为https
      return url.replace("http://", "https://");
    } else {
      // 如果已经是https，则返回原URL
      return url;
    }
  },
  /** 分享给好友 */
  shareFile: function () {
    xhs.shareFileMessage({
      filePath: this.data.filePath,
      fileName: this.data.name,
      success(res) {
        console.log(res);
      },
      fail: console.error,
    });
  },
  /** 添加到收藏 */
  collectFile: function () {
    xhs.addFileToFavorites({
      filePath: this.data.filePath,
      fileName: this.data.name,
      success(res) {
        console.log(res);
      },
      fail: console.error,
    });
  },
  /** 弹窗开关 */
  fileModal: function () {
    this.setData({
      fileModal: !this.data.fileModal,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    xhs.hideShareMenu({
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
